package back

import (
	"fmt"
	"net/http"
	"tmall_go/models"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type IndexController struct{}
type LoginObj struct {
	Name     string
	Password string
}

var loginObj = LoginObj{}

// func (con IndexController) BackIndex(c *gin.Context) {
// 	userInfo := &UserInfo{
// 		Name:    "晓晓",
// 		Sex:     1,
// 		Age:     18,
// 		Address: "北京市东城区115号",
// 		Hoby:    []string{"打篮球", "打羽毛球", "游泳", "吹口琴"},
// 	}
// }

func (con IndexController) IndexLogin(c *gin.Context) {
	// 删除cookie
	c.SetCookie("id", "0", -1, "/", "localhost", false, true)
	c.SetCookie("name", "", -1, "/", "localhost", false, true)
	c.SetCookie("authority", "", -1, "/", "localhost", false, true)
	errStatus := c.Query("error")
	if errStatus == "" {
		pwdObj = PwdObj{}
	}
	c.HTML(http.StatusOK, "backstage/login.html", gin.H{
		"title":     "后台登录页",
		"errStatus": errStatus,
		"info":      loginObj,
		// "date":      1753086904,
	})
}
func (con IndexController) DoLogin(c *gin.Context) {
	userName := c.PostForm("userName")
	password := c.PostForm("password")
	user := models.User{}
	models.DB.Where("name=?", userName).Find(&user)
	fmt.Println("当前用户-user:", user)
	if user.Name == userName {
		// 密码hash对比，不需要解密
		err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
		if err == nil {
			// 登录成功
			loginObj = LoginObj{}
			// cookie存活时间三天
			idStr := fmt.Sprintf("%d", user.Id) // %d用于取整数类型
			c.SetCookie("id", idStr, 60*60*24*3, "/", "localhost", false, true)
			c.SetCookie("name", user.Name, 60*60*24*3, "/", "localhost", false, true)
			c.SetCookie("authority", user.Authority, 60*60*24*3, "/", "localhost", false, true)
			savaObj := models.User{
				Id:         user.Id,
				Name:       user.Name,
				Authority:  user.Authority,
				Sex:        user.Sex,
				Age:        user.Age,
				Address:    user.Address,
				CreateTime: user.CreateTime,
				UpdateTime: user.UpdateTime,
			}
			saveErr := models.SaveDataToRedis("golang_rdb:userInfo", savaObj)
			if saveErr != nil {
				fmt.Println(" 保存数据到redis失败")
			}
			c.Redirect(http.StatusFound, "/back/welcome")
		} else {
			// 登录失败 密码错误
			loginObj = LoginObj{
				Name:     userName,
				Password: password,
			}
			c.Redirect(http.StatusFound, "/back/login?error=2")
		}
	} else {
		// 登录失败 用户名错误
		loginObj = LoginObj{
			Name:     userName,
			Password: password,
		}
		c.Redirect(http.StatusFound, "/back/login?error=1")
	}
}
